﻿using Microsoft.VisualBasic.Devices;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Threading;

namespace RenameByTime
{
    public partial class FrmMain : Form
    {
        private Thread _thread;
        public FrmMain()
        {
            InitializeComponent();
        }
        //想给几百个文件夹里的漫画图片改成按修改日期排序，然后按照修改日期，重命名成数字
        //修改日期，递增
        //对改成123
        private void FrmMain_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            new TextBoxDragDrop(txtPath);
            this.FormClosing += FrmMain_FormClosing;
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null && _thread.IsAlive) _thread.Abort();
        }

        private void btnPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() != DialogResult.OK) return;
            txtPath.Text = dlg.SelectedPath;
        }

        private void workService()
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                pbarSub.Enabled = true;
                pbarMain.Enabled = true;

                Computer compupter = new Computer();
                string path = txtPath.Text.Trim();
                if (!Directory.Exists(path))
                {
                    MessageBox.Show("目录不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                string[] arr = Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories);
                List<string> folders = new List<string>();
                folders.Add(path);
                folders.AddRange(arr);

                HashSet<string> extensions = new HashSet<string>();
                extensions.Add(".jpg");
                extensions.Add(".jepg");
                extensions.Add(".png");

                pbarMain.Value = 0;
                pbarMain.Minimum = 0;
                pbarMain.Maximum = folders.Count;
                foreach (string folder in folders)
                {
                    pbarMain.Value += 1;
                    Dictionary<DateTime, List<string>> dic = new Dictionary<DateTime, List<string>>();
                    string[] files = Directory.GetFiles(folder, "*.*", SearchOption.TopDirectoryOnly);
                    foreach (string file in files)
                    {
                        string extension = Path.GetExtension(file).ToLower().Trim();
                        if (!extensions.Contains(extension)) continue;
                        FileInfo fileInfo = new FileInfo(file);
                        if (!dic.ContainsKey(fileInfo.LastWriteTime))
                            dic.Add(fileInfo.LastWriteTime, new List<string>());
                        dic[fileInfo.LastWriteTime].Add(file);
                    }
                    var timeArr = dic.Keys.ToArray();
                    Array.Sort(timeArr);
                    //Array.Reverse(timeArr);
                    int index = 1;
                    Dictionary<string, int> fnDic = new Dictionary<string, int>();
                    pbarSub.Value = 0;
                    pbarSub.Minimum = 0;
                    pbarSub.Maximum = timeArr.Length;
                    foreach (DateTime dt in timeArr)
                    {
                        pbarSub.Value += 1;
                        foreach (string fn in dic[dt])
                        {
                            string guid = Guid.NewGuid().ToString();
                            string extension = Path.GetExtension(fn);
                            string newName = guid + extension;
                            compupter.FileSystem.RenameFile(fn, newName);
                            string newFn = Path.Combine(Path.GetDirectoryName(fn), newName);
                            fnDic.Add(newFn, index++);
                        }
                    }
                    pbarSub.Value = 0;
                    pbarSub.Minimum = 0;
                    pbarSub.Maximum = fnDic.Keys.Count;
                    foreach (string fn in fnDic.Keys)
                    {
                        pbarSub.Value += 1;
                        string extension = Path.GetExtension(fn);
                        string newName = fnDic[fn] + extension;
                        compupter.FileSystem.RenameFile(fn, newName);
                    }
                }
                MessageBox.Show("操作完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnRename_Click(object sender, EventArgs e)
        {
            _thread = new Thread(new ThreadStart(workService));
            _thread.Start();
        }
    }
}
